<template>
  <div>
    <el-form ref="form" label-width="100px">
      <el-form-item label="SPU名称">{{ spu.spuName }}</el-form-item>
      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格（元）">
        <el-input placeholder="价格（元）" type="number" v-model="skuInfo.price"></el-input>
      </el-form-item>
      <el-form-item label="重量（千克）">
        <el-input placeholder="重量（千克）" v-model="skuInfo.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input type="textarea" rows="4" placeholder="规格描述" v-model="skuInfo.skuDesc"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form :inline="true" ref="form" label-width="80px">
          <el-form-item :label="attr.attrName" v-for="(attr, index) in attrInfoList" :key="attr.id">
            <!-- v-model通过 :value，收集 skuInfo中需要的属性值 -->
            <el-select placeholder="请选择" v-model="attr.attrIdAndValueId">
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="(attrValue, index) in attr.attrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form :inline="true" ref="form" label-width="80px">
          <el-form-item :label="saleAttr.saleAttrName" v-for="(saleAttr, index) in spuSaleAttrList" :key="saleAttr.id">
            <el-select placeholder="请选择" v-model="saleAttr.saleAttrIdAndAttrValueId">
              <el-option
                :label="attrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${attrValue.id}`"
                v-for="(attrValue, index) in saleAttr.spuSaleAttrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table style="width: 100%" border :data="spuImageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" prop="prop" width="80" align="center"></el-table-column>
          <el-table-column prop="prop" label="图片" width="width">
            <template slot-scope="{row,$index}">
              <img :src="row.imgUrl" alt="暂无" style="width: 100px" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" width="width"></el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" v-if="!row.isDefault" @click="changeDefault(row)">设为默认</el-button>
              <el-button v-else size="mini">默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <!-- 根据 isDefault属性，二选一 -->
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SkuForm',
  data() {
    return {
      // 初始表单数据部分
      spuImageList: [],
      spuSaleAttrList: [],
      attrInfoList: [],
      // 需要收集并上传的 skuInfo
      skuInfo: {
        // 第一类：父组件给的数据，来自传过来的spu
        category3Id: 0,
        spuId: 0,
        tmId: 0,
        // 第二类，表单中v-model双向绑定收集
        skuName: '',
        price: 0,
        weight: '',
        skuDesc: '',
        // 第三类
        skuDefaultImg: 'string',
        skuImageList: [
          {
            id: 0,
            imgName: 'string',
            imgUrl: 'string',
            isDefault: 'string',
            skuId: 0,
            spuImgId: 0
          }
        ],
        skuAttrValueList: [
          {
            attrId: 0,
            valueId: 0
          }
        ],
        skuSaleAttrValueList: [
          {
            saleAttrId: 0,
            saleAttrValueId: 0
          }
        ]
      },
      spu: {},
      // 收集选中的图片信息列表，提交给 skuInfo时需要整理数据
      imgList: []
    }
  },
  methods: {
    // 获取初始表单数据
    async getSkuData(c1Id, c2Id, spu) {
      // 获取父组件传来的spu中的数据
      this.spu = spu
      this.skuInfo.category3Id = spu.category3Id
      this.skuInfo.spuId = spu.id
      this.skuInfo.tmId = spu.tmId
      // 获取图片列表
      const result0 = await this.$API.spu.reqSpuImageList(spu.id)
      if (result0.code === 200) {
        // 需要为每个图片信息，添加 isDefault属性
        const arr = result0.data
        arr.forEach(item => {
          item.isDefault = 0
        })
        this.spuImageList = arr
      }
      // 获取销售属性列表
      const result1 = await this.$API.spu.reqSpuSaleAttrList(spu.id)
      if (result1.code === 200) {
        this.spuSaleAttrList = result1.data
      }
      // 获取平台属性列表
      const result2 = await this.$API.spu.reqAttrInfoList(c1Id, c2Id, spu.category3Id)
      if (result2.code === 200) {
        this.attrInfoList = result2.data
      }
    },

    // 图片表格复选框发送变化时的回调函数
    handleSelectionChange(selection) {
      // selection为选中的图片信息，但缺少 isDefault属性
      this.imgList = selection
    },
    // 更改默认图片时的回调函数
    changeDefault(row) {
      this.spuImageList.forEach(item => (item.isDefault = 0))
      row.isDefault = 1
      // 记得同时设置 skuInfo中，默认图片的选项
      this.skuInfo.skuDefaultImg = row.imgUrl
    },
    // 点击取消按钮时的回调函数
    cancel() {
      this.$emit('changeScene1', 0)
      // 同时清除表单数据
      Object.assign(this._data, this.$options.data())
    },
    // 点击保存按钮时的回调函数
    async save() {
      // 整理平台属性，当前存在attrInfoList里的 attrIdAndValueId属性
      this.skuInfo.skuAttrValueList = this.attrInfoList.reduce((prev, item) => {
        if (item.attrIdAndValueId) {
          const [attrId, valueId] = item.attrIdAndValueId.split(':')
          prev.push({ attrId, valueId })
        }
        return prev
      }, [])
      // 整理销售属性，即spuSaleAttrList中的 saleAttrIdAndAttrValueId 属性
      this.skuInfo.skuSaleAttrValueList = this.spuSaleAttrList.reduce((prev, item) => {
        if (item.saleAttrIdAndAttrValueId) {
          const [saleAttrId, saleAttrValueId] = item.saleAttrIdAndAttrValueId.split(':')
          prev.push({ saleAttrId, saleAttrValueId })
        }
        return prev
      }, [])
      // 整理图片列表
      this.skuInfo.skuImageList = this.imgList.map(item => {
        return {
          imgName: item.imgName,
          imgUrl: item.imgUrl,
          isDefault: item.isDefault,
          spuImgId: item.id
        }
      })
      // 发送请求
      const result = await this.$API.spu.reqAddsku(this.skuInfo)
      if (result.code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        this.$emit('changeScene1', 0)
      }
    }
  }
}
</script>

<style></style>
